#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2023/04/04
# @Author  : Tuut
# @Email   : 49616026@qq.com
# @File    : MyEmailConfig.py

import os
## from smtplib import SMTP_SSL
import smtplib
import imaplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from loguru import logger

# 获取当前月份
batch = time.strftime("%Y-%m", time.localtime())
suffix = time.strftime("%Y%m", time.localtime())


#  邮件服务配置工厂类
#  邮件服务连接并查询
class MyEmailConfig:
    host_server = ''
    host_user = ''
    passwd = ''
    sender_mail = ''
    smtp = {}

    def __init__(self, host_server, host_user, passwd, sender_mail):
        # qq邮箱smtp服务器
        self.host_server = host_server
        # sender_qq为发件人的qq号码
        self.host_user = host_user
        # 第三方客户端登录时需要的授权码，不是qq密码
        self.passwd = passwd
        # 发件人的邮箱
        self.sender_mail = sender_mail

    @staticmethod
    def get_pool() -> smtp:
        # ssl登录
        smtp = smtplib.SMTP_SSL(host=MyEmailConfig.host_server, port=465)
        # set_debuglevel()是用来调试的。参数值为1表示开启调试模式，参数值为0关闭调试模式，
        smtp.set_debuglevel(0)
        smtp.ehlo(MyEmailConfig.host_server)
        smtp.login(MyEmailConfig.host_user, MyEmailConfig.passwd)
        return smtp

    def send_email(self, areceiver, acc, mail_type, email_content, subject):
        smtp = self.get_pool()
        """
        发送邮件
        :param email_addr: 收件人邮箱地址
        :param email_content: 需要发送的正文内容
        :param name: 收件人姓名
        :param mail_type: plain(简单的⽂字内容)、html(超文本) 邮件对象.attach(文字对象)
        :return:
        """
        sender_user_mail = 'it@vpclub.cn'
        receiver_mail = areceiver.split(',') + acc.split(',')
        message = MIMEText(email_content, mail_type, 'utf-8')
        message['From'] = sender_user_mail  # 发件人
        message['To'] = ','.join(receiver_mail)  # 收件人邮箱
        message['Cc'] = acc
        message['from'] = 'it'
        message["Subject"] = subject  # 邮件标题
        try:
            smtp.sendmail(from_addr=self.host_user, to_addrs=areceiver, msg=message.as_string())
            smtp.quit()
            msg = f'发送成功，时间: {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}---->{areceiver}'
            with open(f'logs/success_log_{suffix}.txt', 'a', encoding='utf8') as f:
                f.write(msg)
                f.write('\n')
                f.close()
            time.sleep(0.5)
        except Exception as e:
            logger.error(f'发送失败--->{areceiver}\n原因：{e}')
            item = {}
            item['email'] = areceiver
            item['error_reason'] = e
            item['date'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            with open(f'logs/error_log_{suffix}.txt', 'a', encoding='utf8') as f:
                f.write(str(item))
                f.write('\n')
                f.close()
            with open(f'tmp/mail_blackList.txt', 'a', encoding='utf8') as f:
                f.write(str(areceiver))
                f.write("\n")
                f.close()

    # 发送邮件
    def send_file_mail(self, areceiver, acc, file_path,file_name, mail_msg, mail_title):
        if None == mail_title:
            return {'code': 500, 'data': [], 'message': "请填写邮件标题"}
        """
           配置邮件信息
           :return: 消息对象
           """
        # 企业邮箱配置
        sender_user_mail = MyEmailConfig.sender_mail
        receiver_user_mail = areceiver.split(',') + acc.split(',')
        message = MIMEMultipart('related')
        message['From'] = sender_user_mail
        message['To'] = areceiver
        message['Cc'] = acc
        message['Subject'] = mail_title
        msg = MIMEText(mail_msg, _subtype='html', _charset='utf-8')
        message.attach(msg)
        _content = ''
        with open(file_path, 'rb') as _f:
            _content = _f.read()
            _f.close()
        att = MIMEText(_content, 'base64', 'utf-8')
        att['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        att.add_header('Content-Disposition', 'attachment', filename=file_name)  # 添加到header信息
        message.attach(att)
        try:
            smtp = self.get_pool()
            smtp.sendmail(sender_user_mail, receiver_user_mail, message.as_string())
            smtp.quit()
            msg = mail_msg
            with open(f'logs/success_log_{suffix}.txt', 'a', encoding='utf8') as f:
                f.write(msg)
                f.write('\n')
                f.close()
            time.sleep(0.5)
            print("发送成功")
        except Exception as e:
            logger.error(f'发送失败--->\n原因：{e}')
            item = {'email': receiver_user_mail,
                    'error_reason': e,
                    'date': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}
            with open(f'logs/error_log_{suffix}.txt', 'a', encoding='utf8') as f:
                f.write(str(item))
                f.write('\n')
                f.close()

if __name__ == '__main__':
    # 连接到IMAP服务器
    mail = imaplib.IMAP4_SSL('imap.qq.com')
    # 登录
    mail.login('49616026@qq.com', 'erydnykdxmkqbjdi')
    # 选择邮箱
    mail.select('INBOX')
    # 搜索邮件
    result, data = mail.search(None, '火商云用户注册邮件')
    # 遍历邮件ID
    for num in data[0].split():
        # 获取邮件内容
        result, data = mail.fetch(num, '(RFC822)')
        raw_email = data[0][1]
        # 解析邮件内容
        # ...
    # 关闭连接
    mail.close()
    mail.logout()